package com.yjzx.util.common.util.file;

import com.yjzx.util.common.util.StringUtils;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.io.ClassPathResource;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;

import java.io.File;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Properties;
import java.util.stream.Collectors;

/**
 * @author guozhi
 * @date 2025/2/13
 * @description yaml处理
 */
public class YamlUtil {

    public final static YamlPropertiesFactoryBean FACTORY_BEAN = new YamlPropertiesFactoryBean();

    public static Properties getProperties(String name) {
        Properties properties = null;
        try {
            FACTORY_BEAN.setResources(new ClassPathResource(name));
            properties = FACTORY_BEAN.getObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return properties;
    }

    public static Properties getProperties(String... names) {
        Properties properties = null;
        try {
            if (names != null&& names.length > 0){
                ClassPathResource[] array = Arrays.stream(names).filter(StringUtils::isNotBlank)
                        .map(ClassPathResource::new)
                        .toArray(ClassPathResource[]::new);
                FACTORY_BEAN.setResources(array);
                properties = FACTORY_BEAN.getObject();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return properties;
    }
    public static Yaml propertiesToYaml(Properties properties){
        DumperOptions options = new DumperOptions();
        options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);

        return new Yaml(options);
    }
    public static void writeToOutput(OutputStream os,  Properties properties) {
        writeToOutput(os, Charset.defaultCharset(), properties);
    }
    public static void writeToOutput(OutputStream os, Charset cs, Properties properties) {
        try (OutputStreamWriter writer = new OutputStreamWriter(os,cs)){
            writeToWriter(writer, properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void writeToWriter(Writer writer, Properties properties) {
        try {
            Yaml yaml = propertiesToYaml(properties);
            yaml.dump(properties);
            yaml.dump(properties, writer);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
